package com.wuye.web.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuye.utils.SystemConstant;
import com.wuye.web.system.entity.LiveUser;
import com.wuye.web.system.entity.SysUser;
import com.wuye.web.system.mapper.LiveUserMapper;
import com.wuye.web.system.mapper.SysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private LiveUserMapper liveUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //System.out.println("username:  "+username);
        //接收到到username是 admin:1 1代表物主身份，0代表业主身份获取用户身份
        //通过username接受用户名和用户类别，并用：分开，
        //将字符串分割获得用户名和用户类型
        Integer userType = Integer.parseInt(username.substring(username.indexOf(":") + 1)) ;
        username = username.substring(0,username.indexOf(":"));
        //System.out.println(username);

        //根据用户类型来进行分别查询
        if (userType == SystemConstant.USER_TYPE_WUZHU){
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysUser::getUsername,username);
            SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

            //System.out.println("用户信息："+sysUser);

            //没有这个用户名对应的用户时：
            if (Objects.isNull(sysUser)){
                throw new RuntimeException("用户名错误！");
            }
            return sysUser;
        }else if (userType == SystemConstant.USER_TYPE_YEZHU){
            //queryWrapper是mybatis plus中实现查询的对象封装操作类
            QueryWrapper<LiveUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(LiveUser::getUsername,username);
            LiveUser liveUser = liveUserMapper.selectOne(queryWrapper);
            if (Objects.isNull(liveUser)){
                throw new RuntimeException("用户名错误！");
            }
            return liveUser;
        }else {
            return null;
        }
    }
}
